package team.wuyou.util.jdbc;

import java.lang.reflect.Field;
import java.sql.*;

public class CommonJDBCUtil {

    private static final String JDBC_URL = Propertity.url;
    private static final String JDBC_USER = Propertity.username;
    private static final String JDBC_PASSWORD = Propertity.password;



    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
    }

    // 关闭数据库资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    // 根据 SQL 类型执行操作
    public static void executeSql(String sql, Object... params) throws SQLException {
        Connection connection = null;

        try {
            connection = getConnection();
            String sqlType = getSqlType(sql);

            switch (sqlType) {
                case "SELECT":
                    executeQuery(sql, params);
                    break;
                case "INSERT":
                    executeUpdate(sql, params);
                    break;
                case "UPDATE":
                    executeUpdate(sql, params);
                    break;
                case "DELETE":
                    executeUpdate(sql, params);
                    break;
                default:
                    System.out.println("Unsupported SQL type: " + sqlType);
            }
        } finally {
            close(connection, null, null);
        }
    }

    // 获取 SQL 类型
    private static String getSqlType(String sql) {
        String[] words = sql.trim().split("\\s+");
        if (words.length > 0) {
            return words[0].toUpperCase();
        }
        return "";
    }
    // 执行查询操作
    public static ResultSet executeQuery(String sql, Object... params) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            resultSet = preparedStatement.executeQuery();
            return resultSet;
        } catch (SQLException e) {
            close(connection, preparedStatement, resultSet);
            throw e;
        }
    }

    // 执行更新操作
    public static int executeUpdate(String sql, Object... params) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(sql);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            close(connection, preparedStatement, null);
            throw e;
        }
    }
    // 根据 SQL 类型执行操作
    public static int insert(Object entity) throws SQLException {
        Connection connection = null;
         int result = 0;
        try {
            connection = getConnection();

            Class<?> clazz = entity.getClass();
            String tableName = clazz.getSimpleName(); // 假设表名与类名相同

            // 构建 SQL 语句
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append("INSERT INTO ").append(tableName).append(" (");

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                sqlBuilder.append(field.getName()).append(", ");
            }
            sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length());
            sqlBuilder.append(") VALUES (");

            for (Field field : fields) {
                sqlBuilder.append("?, ");
            }
            sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length());
            sqlBuilder.append(")");
            System.out.println("sqlBuilder:"+sqlBuilder);
            // 执行 SQL 语句
            try (PreparedStatement preparedStatement = connection.prepareStatement(sqlBuilder.toString())) {
                int parameterIndex = 1;
                for (Field field : fields) {
                    field.setAccessible(true);
                    Object value = field.get(entity);
                    preparedStatement.setObject(parameterIndex++, value);
                }

                 result = preparedStatement.executeUpdate();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {

            close(connection, null, null);
            return result;
        }
    }
    // 开启事务
    public static void beginTransaction(Connection connection) throws SQLException {
        if (connection != null) {
            connection.setAutoCommit(false);
        }
    }

    // 提交事务
    public static void commitTransaction(Connection connection) throws SQLException {
        if (connection != null) {
            connection.commit();
        }
    }

    // 回滚事务
    public static void rollbackTransaction(Connection connection) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

